package com.wuyangnju.lj.simulation.master.model;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;

public class Slaves {
	private List<Slave> slaves = new LinkedList<Slave>();

	public void registerSlave(Slave slave) {
		slaves.add(slave);
		Collections.sort(slaves);
	}

	private int totalThreads() {
		int count = 0;
		for (Slave slave : slaves) {
			count += slave.getThreadNumber();
		}
		return count;
	}

	private int startCount(String ip, int threadId) {
		int count = 0;
		for (Slave slave : slaves) {
			if (!slave.getIp().equals(ip)) {
				count += slave.getThreadNumber();
			} else {
				count += threadId;
				break;
			}
		}
		return count;
	}

	public double startPercent(String ip, int threadId) {
		return startCount(ip,threadId) / (totalThreads() * 1.0);
	}

	public double endPercent(String ip, int threadId) {
		return (1 + startCount(ip, threadId)) / (totalThreads() * 1.0);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		NetworkInterface ni = null;
		try {
			ni = NetworkInterface.getByName("eth0");
		} catch (SocketException e) {
			e.printStackTrace();
		}
		Enumeration<InetAddress> inas = ni.getInetAddresses();
		Inet4Address in4a = null;
		while (inas.hasMoreElements()) {
			InetAddress ina = inas.nextElement();
			if (ina instanceof Inet4Address) {
				in4a = (Inet4Address) ina;
			}
		}
		System.out.println(in4a.getHostAddress());
	}
}
